package com.jgzx.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jgzx.common.R;
import com.jgzx.domain.ListVO;
import com.jgzx.domain.dto.IdDTO;
import com.jgzx.domain.dto.UserDTO;
import com.jgzx.domain.po.UserPO;
import com.jgzx.domain.vo.UserVO;
import com.jgzx.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class UserService extends ServiceImpl<UserMapper,UserPO> {
    /**
     * 查询用户列表
     */
    public R<ListVO<UserVO>> listAll() {
        List<UserVO> records = this.baseMapper.listAll();
        ListVO<UserVO> UserVOList = new ListVO<>(records);
        log.info("查询用户列表:records={}", UserVOList);
        return R.ok(UserVOList);
    }
    /**
     * 查询用户详情
     */
    public R<UserVO> findUser(IdDTO idDTO){
        UserVO userVo = this.baseMapper.finduser(idDTO.getUserId());
        log.info("用户详情={}",userVo);
        return R.ok(userVo);
    }
    /**
     * 增加用户
     */
    @Transactional
    public R<UserVO> AddUser(UserDTO userDTO){
        if(! ObjectUtil.isNull(userDTO.getUserId())){
            return R.fail("新增用户主键不能为空");
        }
        UserPO userPO = BeanUtil.copyProperties(userDTO,UserPO.class);
        this.save(userPO);
        return findUser(new IdDTO(userDTO.getUserId()));
    }
    /**
     * 删除用户
     */
    @Transactional
    public R DeleteUser(long userid){
        UserPO alreaduserPO = lambdaQuery().eq(UserPO::getUserId,userid).one();
        if(ObjectUtil.isNull(alreaduserPO)){
            return R.fail("数据已经被更改");
        }
        this.removeById(userid);
        return R.ok();
    }
    /**
     * 更改用户信息
     */
    @Transactional
    public R<UserVO> UpdateUser(UserDTO userDTO){
        if(ObjectUtil.isNull(userDTO.getUserId())){
            return R.fail("更新用户信息要存在用户主键ID");
        }

        UserPO userPOaalread = lambdaQuery().eq(UserPO::getUserId,userDTO.getUserId()).one();
        if(ObjectUtil.isNull(userPOaalread)){
            return R.fail("用户数据已被修改");
        }
        UserPO userPO = BeanUtil.copyProperties(userDTO,UserPO.class);
        this.updateById(userPO);
        return findUser(new IdDTO(userDTO.getUserId()));
    }
}
